import SqLite from "./index";

const dbTable = "ringData";

/**
 * id  唯一
 * cmd 蓝牙指令
 * sub 子命令
 * data 有效数据帧
 */
const column = ["id", "cmd", "sub", "data", "ts"];
const tableData = "'id' INTEGER PRIMARY KEY AUTOINCREMENT, cmd varchar(2), sub varchar(2), data TEXT, ts INTEGER";

const openSqLite = async () => {
	if (SqLite.isOpen()) {
		return await SqLite.createTable(dbTable, tableData);
	} else {
		try {
			await SqLite.openSqlite();
		} catch (error) {
			console.log("openSqLite error", error);
		}
		return await SqLite.createTable(dbTable, tableData);
	}
};

const closeSqlite = () => {
	return SqLite.closeSqlite();
};

const insertData = async (cmd, sub, data, ts) => {
	const result = await SqLite.selectTableData(dbTable, "data", data, "ts", ts);
	return SqLite.insertTableData(dbTable, `'${cmd}', '${sub}', '${data}', ${ts}`, "cmd, sub, data, ts");
};

const insertDataBatch = (sql) => {
	return SqLite.insertTableDataBatch(dbTable, sql, "cmd, sub, data, ts");
};

const selectData = ({ cmd, sub, ts, symbol = "=", sort = "DESC", order = "ts" }) => {
	let con = "";
	if (cmd) {
		con += `cmd = '${cmd}' `;
		if (sub) {
			con += `AND sub = '${sub}' `;
		}
	}
	if (ts && symbol) {
		if (symbol !== "=" || symbol !== ">=" || symbol !== "<=" || symbol !== "<" || symbol !== ">") {
			symbol = "=";
		}
		con += `AND ts ${symbol} ${ts} `;
	}
	if (column.includes(order)) {
		con += `ORDER BY ${order} `;
	}

	if (sort === "DESC" || sort === "ASC") {
		con += `${sort} `;
	}

	return SqLite.selectTableDataByCustomConditions(dbTable, con);
};

// const deleteData = (ts, symbol = '=') => {
// 	if ()
// 	SqLite.deleteTableDataByCustomConditions(dbTable, id);
// }

/**
 *  删除传入时间7天前的数据
 * @param {*} ts
 * @returns
 */
const deleteDataBefore7 = (ts) => {
	if (!isValidTimestamp(ts)) throw new TypeError("Invalid timestamp");
	return SqLite.deleteTableDataByCustomConditions(dbTable, `ts < ${ts}`);
};

function isValidTimestamp(ts) {
	// 检查类型
	if (typeof ts !== "number") {
		return false;
	}

	// 检查范围（假设我们只考虑 1970 年到 2038 年的有效时间戳）
	const minTimestamp = 0; // 1970-01-01 00:00:00 UTC
	const maxTimestamp = 2147483647; // 2038-01-19 03:14:07 UTC (32-bit signed integer)

	if (ts < minTimestamp || ts > maxTimestamp) {
		return false;
	}

	// 检查转换为日期是否有效
	const date = new Date(ts * 1000); // 如果是秒级时间戳，乘以 1000 转换为毫秒
	return date instanceof Date && !isNaN(date);
}

export default { openSqLite, closeSqlite, insertData, selectData, insertDataBatch, deleteDataBefore7 };
